/**
 * @Author: easten
 * @Created: 2024-05-26 11:15:31
 * @Description: 权限维护管理
 *
 */
import classnames from "classnames";
import React, { useState, useEffect, useMemo } from "react";
import {
  AddCircleIcon,
  ChevronDownIcon,
  ChevronRightIcon,
  MinusCircleIcon,
  RefreshIcon,
  SearchIcon,
} from "tdesign-icons-react";
import {
  Button,
  EnhancedTable,
  Input,
  Loading,
  Popconfirm,
  Space,
  message,
} from "tdesign-react";
// import RoleDrawer from './RoleDrawer';
import { ModuleCommonProps } from "_common/DataType";
import { SysPermission } from "_common/entity";
import { ApiPermission } from "_common/api/sys";
import { relationNodeArray2Tree } from "utils/treeUtil";
import { TableTitle } from "components";
import PermissionDrawer from "./PermissionDrawer";
const SysPermissionComp: React.FC<ModuleCommonProps> = (props) => {
  const { axios, className } = props;
  const [selectedRow, setSelectedRow] = useState<SysPermission | undefined>();
  const [lazyLoadingData, setLazyLoadingData] =
    useState<SysPermission | null>();
  const [expandedTreeNodes, setExpandedTreeNodes] = useState<any>([]);
  const [customTreeExpandAndFoldIcon] = useState(false);
  const [data, setData] = useState<SysPermission[]>();
  const [visible, setVisible] = useState(false);
  const [edit, setEdit] = useState(false);

  const apiPermission = new ApiPermission(axios!);

  useEffect(() => {
    getPermissionList();
  }, []);

  const getPermissionList = async () => {
    setData([]);
    const response = await apiPermission.getList();
    if (response && response.code === 200 && response.data) {
      const treeArr = relationNodeArray2Tree(response.data);
      setData(treeArr as any);
    }
  };
  // 删除用户
  const deleteRole = async (id: number) => {
    const response = await apiPermission.delete(id);
    if (response && response.code === 200) {
      message.success("删除成功");
      getPermissionList();
    }
  };

  // @ts-ignore
  const renderTreeExpandAndFoldIcon = ({ type, row }) => {
    if (lazyLoadingData?.id === row?.id) {
      return <Loading size="14px" />;
    }
    return type === "expand" ? <ChevronRightIcon /> : <ChevronDownIcon />;
  };

  function onTreeExpandChange(context: any) {
    if (context.row.children === true) {
      setLazyLoadingData(context.row);
      const timer = setTimeout(() => {
        setLazyLoadingData(null);
        clearTimeout(timer);
      }, 200);
    }
  }

  const treeExpandIconRender = useMemo(() => {
    // 自定义展开图标
    if (customTreeExpandAndFoldIcon) {
      return renderTreeExpandAndFoldIcon;
    }
    return lazyLoadingTreeIconRender;
  }, [lazyLoadingData, customTreeExpandAndFoldIcon]);

  // 懒加载图标渲染
  function lazyLoadingTreeIconRender(params: any) {
    const { type, row } = params;
    if (lazyLoadingData?.id === row?.id) {
      return <Loading size="14px" />;
    }
    return type === "expand" ? (
      <AddCircleIcon color="#1781F0" />
    ) : (
      <MinusCircleIcon color="#1781F0" />
    );
  }

  return (
    <div className={classnames(className)}>
      <div className="flex flex-row justify-between mb-4">
        <TableTitle text="权限列表" />
        <Space size={5}>
          <Input
            suffixIcon={<SearchIcon />}
            placeholder="请输入要搜索的角色名称"
            onChange={() => {
              // setRoleName(v);
            }}
          />
          <Button
            onClick={() => {
              setVisible(true);
              setEdit(false);
              setSelectedRow(undefined);
            }}
          >
            添加权限
          </Button>
          <Button
            icon={<RefreshIcon />}
            variant="outline"
            onClick={() => {
              getPermissionList();
            }}
          ></Button>
        </Space>
      </div>
      <EnhancedTable<SysPermission>
        bordered
        columns={[
          {
            colKey: "index",
            title: "序号",
            ellipsis: true,
            width: 70,
            cell: ({ rowIndex }) => {
              let _index = rowIndex + 1;
              return <span>{_index}</span>;
            },
          },
          {
            colKey: "name",
            title: "权限名称",
            ellipsis: true,
          },
          {
            colKey: "code",
            title: "权限编码",
          },
          {
            colKey: "fullCode",
            title: "完整编码",
          },
          {
            align: "center",
            fixed: "right",
            width: 220,
            colKey: "op",
            title: "操作",
            cell({ row }) {
              return (
                <Space size={0}>
                  <Button
                    theme="success"
                    variant="text"
                    onClick={() => {
                      setVisible(true);
                      setEdit(false);
                      setSelectedRow(row);
                    }}
                  >
                    添加
                  </Button>
                  <Button
                    theme="success"
                    variant="text"
                    onClick={() => {
                      setVisible(true);
                      setEdit(true);
                      setSelectedRow(row);
                    }}
                  >
                    编辑
                  </Button>
                  <Popconfirm
                    content="确认删除吗"
                    destroyOnClose
                    placement="top"
                    showArrow
                    theme="danger"
                    onConfirm={() => deleteRole(row.id)}
                  >
                    <Button theme="danger" variant="text">
                      删除
                    </Button>
                  </Popconfirm>
                </Space>
              );
            },
          },
        ]}
        data={data}
        rowKey="id"
        tree={{
          childrenKey: "children",
          treeNodeColumnIndex: 1,
          indent: 30 /** , defaultExpandAll: true */,
        }}
        expandedTreeNodes={expandedTreeNodes}
        onExpandedTreeNodesChange={setExpandedTreeNodes}
        // @ts-ignore
        treeExpandAndFoldIcon={treeExpandIconRender}
        hover
        onTreeExpandChange={onTreeExpandChange}
      />
      <PermissionDrawer
        open={visible}
        axios={axios}
        edit={edit}
        value={selectedRow}
        onSuccess={() => {
          setVisible(false);
          getPermissionList();
        }}
      />
    </div>
  );
};
export default SysPermissionComp;
